<template>
  <div class="cl-collapse">
    <slot></slot>
  </div>
</template>
<script setup lang="ts">
import { ref, provide, watch } from 'vue'
import type { NameType, CollapseProps, CollapseEmits } from './types'
import { collapseContextKey } from './types'
defineOptions({ name: 'CLCollapse' })
const props = defineProps<CollapseProps>()
const emits = defineEmits<CollapseEmits>()
const activeNames = ref<NameType[]>(props.modelValue)
if (props.modelValue && activeNames.value.length > 1) {
  console.warn('[Collapse warn]: modelValue can only be a single value')
}
watch(
  () => props.modelValue,
  () => {
    activeNames.value = props.modelValue
  }
)
const handleItemClick = (item: NameType) => {
  let _activeNames = [...activeNames.value]
  if (props.accordion) {
    _activeNames = [_activeNames[0] == item ? '' : item]
    activeNames.value = _activeNames
  } else {
    const index = _activeNames.indexOf(item)
    if (index > -1) {
      _activeNames.splice(index, 1)
    } else {
      _activeNames.push(item)
    }
    activeNames.value = _activeNames
  }
  emits('update:modelValue', activeNames.value)
  emits('change', activeNames.value)
}
provide(collapseContextKey, { activeNames, handleItemClick })
</script>
